package cate.game.framework.share;

import cate.game.GameBody;
import cate.game.ManyGame;
import cate.game.demo.batch.BatchExcelReload;
import cate.game.demo.batch.GameBatchCmdHandlers;
import cp.solution.business.game.cmd.GameBatchCmd;
import cp.solution.business.game.cmd.GameCmdExecutor;
import cp.solution.rpc.path.RpcSharePath;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.concurrent.Callable;

@Slf4j
public class ShareLogic {

    private ManyGame games;
    public void setup(ManyGame games) {
        this.games = games;
    }

    public void everyDozenSeconds() {
    }

    public void batchCmd(GameBatchCmd cmd) {
        log.info("收到批量执行的指令 : {}", cmd);
        Callable<String> processRun = null;
        if(StringUtils.equals(GameBatchCmd.TYPE_EXCEL_RELOAD, cmd.type)) {
            processRun = () -> BatchExcelReload.exe(cmd);
        }
        long processCost = 0;
        String processMessage = null;
        if(processRun != null) {
            long beginTime = System.currentTimeMillis();
            try {
                processMessage = processRun.call();
            } catch (Exception e) {
                log.error("", e);
                processMessage = e.getMessage();
            }
            processCost = System.currentTimeMillis() - beginTime;
        }

        for(GameBody game : this.games.getAll()) {
            GameCmdExecutor executor = new GameCmdExecutor();
            executor.srvId = game.config.srvId;
            executor.srvName = game.config.gs.getName();
            executor.groupCode = game.config.gs.getGroupCode();
            executor.accept = true;
            executor.done = false;
            executor.message = "即将执行指令";
            try {
                game.rpcSend().fireAndForgetConsole(RpcSharePath.GAME_BATCH_CMD_REPORT_G2C, executor);
            } catch (Exception e) {
                log.error("", e);
            }
            //
            if(processRun != null) {
                executor.costTime = processCost;
                executor.message = processMessage;
            } else {
                long beginTime = System.currentTimeMillis();
                executor.message = GameBatchCmdHandlers.getExecutor(cmd).exe(game, cmd);
                long cost = System.currentTimeMillis() - beginTime;
                executor.costTime = cost;
            }
            //
            executor.done = true;
            try {
                game.rpcSend().fireAndForgetConsole(RpcSharePath.GAME_BATCH_CMD_REPORT_G2C, executor);
            } catch (Exception e) {
                log.error("", e);
            }
        }
    }

    public void batchMail(String msgFromConsole) {
        for(GameBody game : this.games.getAll()) {
            long beginTime = System.currentTimeMillis();
            game.mail.batchMail.load(msgFromConsole);
            log.info("游戏服({}) 执行批量邮件 耗时{}ms", game.config.srvId, System.currentTimeMillis() - beginTime);
        }
    }
}
